{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## NumPy\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "%matplotlib inline\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.arange(10)\n",
    "a\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.ones((4, 4, 4, 4))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.zeros(2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(np.linspace(0, 1, 5))  # 等比数列\n",
    "print(np.logspace(0, 1, 5))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.diag([1, 2, 3, 4]).ndim\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]])\n",
    "print(np.max(a))\n",
    "print(np.min(a))\n",
    "print(np.average(a))\n",
    "print(np.sum(a))\n",
    "print(np.prod(a))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.random.random(8)\n",
    "b = np.random.random(8)\n",
    "print(a)\n",
    "print(b)\n",
    "a*b\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([np.random.randint(1, 10) for i in range(4)])\n",
    "print(a)\n",
    "b = np.array([np.random.randint(1, 10) for i in range(4)])\n",
    "print(b)\n",
    "# 点积\n",
    "print(\"a.b=\", np.dot(a, b))\n",
    "print(\"a.b=\", np.sum(a*b))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 范数\n",
    "a = np.array([1, 2, 3, 4])\n",
    "\n",
    "print(\"L1范数: \", np.linalg.norm(a, 1))\n",
    "print(\"L2范数: \", np.linalg.norm(a))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([[1, 2, 3, 4], [2, 3, 4, 5]])\n",
    "b = np.array([[1, 2], [1, 2], [1, 2], [1, 2]])\n",
    "# 矩阵点积\n",
    "print(x := np.dot(a, b))\n",
    "# 转置\n",
    "print(x.T)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([[1, 2], [3, 4]])\n",
    "# 矩阵行列式\n",
    "print(np.linalg.det(a))\n",
    "# 矩阵的逆矩阵\n",
    "print(np.linalg.inv(a))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "def arraw(s, l, clr): return plt.quiver(\n",
    "    s[0], s[1], l[0], l[1], angles='xy', scale_units='xy', scale=1, color=clr)\n",
    "\n",
    "\n",
    "s = np.array([0, 0])\n",
    "a = np.array([2, 3])\n",
    "print(a)\n",
    "A = np.array([[2, -1], [2, -2]])\n",
    "# 线性变换``\n",
    "b = np.array(np.dot(A, a))\n",
    "print(b)\n",
    "\n",
    "arraw(s, a, 'black')\n",
    "arraw(s, b, 'blue')\n",
    "plt.xlim([-3, 3])\n",
    "plt.ylim([-3, 3])\n",
    "plt.grid()\n",
    "# plt.axes().set_aspect('equal')\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([[3, 1], [2, 4]])\n",
    "ev = np.linalg.eig(a)\n",
    "# 特征值\n",
    "print(ev[0])\n",
    "# 特征向量 (列)\n",
    "print(ev[1])\n",
    "\n",
    "# L2范数为1\n",
    "print(np.linalg.norm([i[0] for i in ev[1]]))\n",
    "print(np.linalg.norm([i[1] for i in ev[1]]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 余弦相似度\n",
    "def cos_sim(a, b): return np.dot(a, b)/(np.linalg.norm(a)*np.linalg.norm(b))\n",
    "\n",
    "\n",
    "a = np.array([2, 2, 2, 2])\n",
    "b = np.array([1, 1, 1, 1])\n",
    "c = np.array([-1, -1, -1, -1])\n",
    "\n",
    "print(cos_sim(a, b))\n",
    "print(cos_sim(a, c))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(x): return 3 * x**2 + 4*x + 5\n",
    "def df(x): return 6*x + 4\n",
    "\n",
    "\n",
    "p = 1\n",
    "def k(x): return df(p)*x+f(p)-df(p)*p\n",
    "\n",
    "\n",
    "print(type(f))\n",
    "\n",
    "\n",
    "x = np.linspace(-10, 10)\n",
    "plt.plot(x, f(x), label='f')\n",
    "plt.plot(x, df(x), label='df')\n",
    "plt.plot(x, k(x), label='k')\n",
    "plt.legend()\n",
    "\n",
    "plt.xlabel('x', size=14)\n",
    "plt.ylabel('y', size=14)\n",
    "plt.grid()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sigmoid_f(x): return 1/(1+np.exp(-x))\n",
    "def grad_sigmoid_f(x): return (1-sigmoid_f(x))*sigmoid_f(x)\n",
    "\n",
    "\n",
    "x = np.linspace(-10, 10)\n",
    "plt.plot(x, sigmoid_f(x), label='sigmoid')\n",
    "plt.plot(x, grad_sigmoid_f(x), label='grad')\n",
    "plt.legend()\n",
    "\n",
    "plt.xlabel('x', size=14)\n",
    "plt.ylabel('y', size=14)\n",
    "plt.grid()\n",
    "\n",
    "print(grad_sigmoid_f(0))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(x): return x**2-2*x\n",
    "def df(x): return 2*x-2\n",
    "\n",
    "\n",
    "eta = 0.1\n",
    "x = 4.0\n",
    "record_x = []\n",
    "record_y = []\n",
    "for i in range(20):\n",
    "    y = f(x)\n",
    "    record_x.append(x)\n",
    "    record_y.append(y)\n",
    "    x -= eta*df(x)\n",
    "x_f = np.linspace(-2, 4)\n",
    "plt.plot(x_f, f(x_f), linestyle='dashed')\n",
    "plt.scatter(record_x, record_y)\n",
    "\n",
    "plt.xlabel('x', size=14)\n",
    "plt.ylabel('y', size=14)\n",
    "plt.grid()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = []\n",
    "y = []\n",
    "total = 0\n",
    "num_5 = 0\n",
    "n = 5000\n",
    "\n",
    "for i in range(n):\n",
    "    if np.random.randint(6)+1 == 5:\n",
    "        num_5 += 1\n",
    "    total += 1\n",
    "    x.append(i)\n",
    "    y.append(num_5/total)\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.plot(x, [1/6]*n, linestyle='dashed')\n",
    "plt.xlabel('x', size=14)\n",
    "plt.ylabel('y', size=14)\n",
    "plt.grid()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = []\n",
    "y = []\n",
    "num_front = 0\n",
    "total = 0\n",
    "n = 5000\n",
    "\n",
    "for i in range(n):\n",
    "    if np.random.randint(2) == 1:\n",
    "        num_front += 1\n",
    "    total += 1\n",
    "    x.append(i)\n",
    "    y.append(num_front/total)\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.plot(x, [1/2]*n, linestyle='dashed')\n",
    "plt.xlabel('x', size=14)\n",
    "plt.ylabel('y', size=14)\n",
    "plt.grid()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p = [0.1, 0.2, 0.3, 0.1, 0.2, 0.2]\n",
    "v = np.array([np.random.randint(101) for i in range(6)])\n",
    "print(p)\n",
    "print(v)\n",
    "# average expection\n",
    "print(np.dot(p, v))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "v = np.random.randint(0, 100, 5)\n",
    "print(v)\n",
    "# variance 方差\n",
    "print(np.var(v))\n",
    "# standard deviation 标准差\n",
    "print(np.std(v))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.randint(0, 100, 5)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 正态分布 normal distribution\n",
    "v = np.random.normal(0, 1, 10000)\n",
    "plt.hist(v, bins=25)\n",
    "plt.xlabel('x', size=14)\n",
    "plt.grid()\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 幂律\n",
    "\n",
    "$$f(x)=cx^{-k}$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def p_f(c, k, x): return c*x**(-k)\n",
    "\n",
    "\n",
    "x = np.linspace(-100, 0)\n",
    "plt.plot(x, p_f(1, 1, x))\n",
    "x = np.linspace(0, 100)\n",
    "plt.plot(x, p_f(1, 1, x))\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$$\n",
    "Cov(X,Y)=\\frac{1}{n} \\sum_{k=1}^{n}(x_k-\\mu_{kx})(y_k-\\mu_{ky})\n",
    "$$\n",
    "\n",
    "$$Cov>>0 正相关 positive correlation  $$\n",
    "$$Cov==0 相关性不大 $$\n",
    "$$Cov<<0 负相关 negative $$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cov(x, y): return np.average((x-np.average(x))*((y-np.average(y))))\n",
    "\n",
    "\n",
    "x = np.array([5, 7, 4, 6, 8])*10\n",
    "y = np.array([6, 8, 5, 5, 7])*10\n",
    "cov(x, y)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show_cov(cov):\n",
    "    print(\"covariance: \", cov)\n",
    "    average = np.array([0, 0])\n",
    "    cov_matrix = np.array([[1, cov], [cov, 1]])\n",
    "    data = np.random.multivariate_normal(average, cov_matrix, 3000)\n",
    "    # 0列\n",
    "    x = data[:, 0]\n",
    "    y = data[:, 1]\n",
    "    plt.scatter(x, y, marker='x', s=20)\n",
    "    plt.xlabel('x', size=14)\n",
    "    plt.ylabel('y', size=14)\n",
    "    plt.grid()\n",
    "\n",
    "\n",
    "show_cov(0.8)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_cov(0.0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_cov(-0.8)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 相关系数\n",
    "\n",
    "$$\n",
    "r=\\frac{Cov(X,Y)}{\\sigma_X\\sigma_Y}\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.array([5, 7, 4, 6, 8])\n",
    "y = np.array([6, 8, 5, 5, 7])\n",
    "print(\"相关系数\")\n",
    "print(np.corrcoef(x, y))\n",
    "\n",
    "print(cov(x, y)/(np.std(x)*np.std(y)))\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# conditional probabity\n",
    "\n",
    "$$\n",
    "P(A|B)=\\frac{P(A\\bigcap B)}{P(B)}\n",
    "$$\n",
    "\n",
    "# Bayesian formula\n",
    "\n",
    "$$\n",
    "P(B|A)=\\frac{P(A|B)P(B)}{P(A)}=\\frac{P(A\\bigcap B)}{P(A)}\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pb = 0.01/100\n",
    "pa1b = 98/100\n",
    "pa2b_ = 90/100\n",
    "pa1 = pa1b*pb+(1-pa2b_)*(1-pb)\n",
    "pba1 = pa1b*pb/pa1\n",
    "pba1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "%matplotlib inline\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Likelihood\n",
    "\n",
    "$$\n",
    "L=\\prod_{k=1}^np(x_k)\n",
    "$$\n",
    "\n",
    "$$\n",
    "log(L)=\\prod_{k=1}^nlog(p(x_k))\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_data = np.array([2.4, 1.2, 3.5, 2.1, 4.7])\n",
    "y_data = np.zeros(5)\n",
    "\n",
    "\n",
    "def pdf(x, mu=0, sigma=1):\n",
    "    return 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(x-mu)**2/(2*sigma**2))\n",
    "\n",
    "\n",
    "x_pdf = np.linspace(-10, 10)\n",
    "y_pdf = pdf(x_pdf)\n",
    "plt.scatter(x_data, y_data)\n",
    "plt.plot(x_pdf, y_pdf)\n",
    "plt.plot([3, 3], [0, 0.5], 'k--', lw=2.5)\n",
    "plt.plot([-3, -3], [0, 0.5], 'k--', lw=2.5)\n",
    "\n",
    "print(\"lower likelihood\")\n",
    "\n",
    "print(\"Likelihood :\")\n",
    "print(np.prod(pdf(x_data)))\n",
    "\n",
    "print(\"Log Likelihood :\")\n",
    "print(np.sum(np.log(pdf(x_data))))\n",
    "\n",
    "print()\n",
    "print(\"upper likelihood\")\n",
    "\n",
    "mu = np.average(x_data)\n",
    "sigma = np.std(x_data)\n",
    "\n",
    "print(\"Likelihood :\")\n",
    "# use average and sigma\n",
    "print(np.prod(pdf(x_data, mu, sigma)))\n",
    "\n",
    "print(\"Log Likelihood :\")\n",
    "print(np.sum(np.log(pdf(x_data, mu, sigma))))\n",
    "\n",
    "y_pdf = pdf(x_pdf, mu, sigma)\n",
    "\n",
    "plt.plot(x_pdf, y_pdf)\n",
    "plt.plot([x := 3*sigma, x], [0, 0.5], 'r--', lw=1.5)\n",
    "plt.plot([y := -3*sigma, y], [0, 0.5], 'r--', lw=1.5)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "自熵\n",
    "\n",
    "$$\n",
    "I(E)=-log_2P(E)\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# broadcast\n",
    "a1 = np.array([[0, 0, 0], [10, 10, 10], [20, 20, 20]])\n",
    "a2 = np.array([[0, 1, 2]])\n",
    "\n",
    "a1+a2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 傅里叶变换\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "x = np.linspace(0, 2*np.pi, 1000)\n",
    "y = np.sin(x)\n",
    "plt.subplot(1, 3, 1)\n",
    "plt.plot(x, y, color='blue')\n",
    "\n",
    "# 傅里叶变换\n",
    "yf = np.fft.fft(y)\n",
    "plt.subplot(1, 3, 2)\n",
    "plt.plot(yf, color='red')\n",
    "\n",
    "# 傅里叶逆变换\n",
    "y2 = np.fft.ifft(yf)\n",
    "plt.subplot(1, 3, 3)\n",
    "plt.plot(y2, color='green')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "img = cv2.imread('../name.png', 0)\n",
    "\n",
    "\n",
    "plt.subplot(1, 3, 1)\n",
    "plt.axis('off')\n",
    "plt.title('original')\n",
    "plt.imshow(img)\n",
    "\n",
    "\n",
    "# 傅里叶变换\n",
    "f_img = np.fft.fft2(img)\n",
    "f_shift = np.fft.fftshift(f_img)\n",
    "\n",
    "result = 20*np.log(np.abs(f_shift))\n",
    "plt.subplot(1, 3, 2)\n",
    "plt.axis('off')\n",
    "plt.title('fft')\n",
    "plt.imshow(result, cmap='gray')\n",
    "\n",
    "# 傅里叶逆变换\n",
    "f_ishift = np.fft.ifftshift(f_shift)\n",
    "img_back = np.fft.ifft2(f_ishift)\n",
    "img_back = np.abs(img_back)\n",
    "plt.subplot(1, 3, 3)\n",
    "plt.axis('off')\n",
    "plt.title('ifft')\n",
    "plt.imshow(img_back, cmap='gray')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 高通滤波作用：去除低频分量，保留高频分量，\n",
    "# 提高图像的对比度，增强图像的边缘和细节，但是会使图像模糊，\n",
    "# 因为高频分量是图像的细节，去除低频分量后，\n",
    "# 图像的细节也就被去除了，所以图像会变模糊。\n",
    "\n",
    "# 高通滤波器的原理是：将图像的频谱中心点移动到频谱的左上角，\n",
    "# 然后将图像的左上角和右下角的频谱进行交换，\n",
    "# 这样就将图像的低频分量移动到了图像的右下角，\n",
    "# 高频分量移动到了图像的左上角，这样就实现了图像的高通滤波。\n",
    "\n",
    "# 高通滤波器的实现步骤：\n",
    "# 1.将图像的频谱中心点移动到频谱的左上角\n",
    "# 2.将图像的左上角和右下角的频谱进行交换\n",
    "# 3.将图像的频谱进行对数变换，这样可以使图像的对比度更好\n",
    "# 4.将图像的频谱进行归一化处理，这样可以使图像的灰度值在0-255之间\n",
    "\n",
    "# 高通滤波器的实现代码如下：\n",
    "# 1.将图像的频谱中心点移动到频谱的左上角\n",
    "fshift = np.fft.fftshift(f_img)\n",
    "\n",
    "# 2.将图像的左上角和右下角的频谱进行交换\n",
    "rows, cols = img.shape\n",
    "crow, ccol = int(rows / 2), int(cols / 2)  # 中心点\n",
    "fshift[crow - 30:crow + 30, ccol - 30:ccol + 30] = 0\n",
    "\n",
    "# 3.将图像的频谱进行对数变换，这样可以使图像的对比度更好\n",
    "f_ishift = np.fft.ifftshift(fshift)\n",
    "img_back = np.fft.ifft2(f_ishift)\n",
    "img_back = np.abs(img_back)\n",
    "\n",
    "# 4.将图像的频谱进行归一化处理，这样可以使图像的灰度值在0-255之间\n",
    "result = 20 * np.log(np.abs(fshift))\n",
    "result = (result - np.min(result)) / (np.max(result) - np.min(result)) * 255\n",
    "\n",
    "plt.subplot(1, 3, 1)\n",
    "plt.axis('off')\n",
    "plt.title('original')\n",
    "plt.imshow(img, cmap='gray')\n",
    "\n",
    "plt.subplot(1, 3, 2)\n",
    "plt.axis('off')\n",
    "plt.title('fft')\n",
    "plt.imshow(result, cmap='gray')\n",
    "\n",
    "plt.subplot(1, 3, 3)\n",
    "plt.axis('off')\n",
    "plt.title('ifft')\n",
    "plt.imshow(img_back, cmap='gray')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 低通滤波作用：去除高频分量，保留低频分量，\n",
    "# 使图像变模糊，但是可以去除图像中的噪声，\n",
    "# 因为噪声是高频分量，去除高频分量后，\n",
    "# 噪声也就被去除了，所以图像会变模糊。\n",
    "\n",
    "# 低通滤波器的原理是：将图像的频谱中心点移动到频谱的左上角，\n",
    "# 然后将图像的左上角和右下角的频谱进行交换，\n",
    "# 这样就将图像的高频分量移动到了图像的右下角，\n",
    "# 低频分量移动到了图像的左上角，这样就实现了图像的低通滤波。\n",
    "\n",
    "# 低通滤波器的实现代码如下：\n",
    "# 1.将图像的频谱中心点移动到频谱的左上角\n",
    "fshift = np.fft.fftshift(f_img)\n",
    "\n",
    "# 2.将图像的左上角和右下角的频谱进行交换\n",
    "rows, cols = img.shape\n",
    "crow, ccol = int(rows / 2), int(cols / 2)  # 中心点\n",
    "fshift[crow - 30:crow + 30, ccol - 30:ccol + 30] = 0\n",
    "\n",
    "# 3.将图像的频谱进行对数变换，这样可以使图像的对比度更好\n",
    "f_ishift = np.fft.ifftshift(fshift)\n",
    "img_back = np.fft.ifft2(f_ishift)\n",
    "img_back = np.abs(img_back)\n",
    "\n",
    "# 4.将图像的频谱进行归一化处理，这样可以使图像的灰度值在0-255之间\n",
    "result = 20 * np.log(np.abs(fshift))\n",
    "result = (result - np.min(result)) / (np.max(result) - np.min(result)) * 255\n",
    "\n",
    "plt.subplot(1, 3, 1)\n",
    "plt.axis('off')\n",
    "plt.title('original')\n",
    "plt.imshow(img, cmap='gray')\n",
    "\n",
    "plt.subplot(1, 3, 2)\n",
    "plt.axis('off')\n",
    "plt.title('fft')\n",
    "plt.imshow(result, cmap='gray')\n",
    "\n",
    "plt.subplot(1, 3, 3)\n",
    "plt.axis('off')\n",
    "plt.title('ifft')\n",
    "plt.imshow(img_back, cmap='gray')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# openCV 傅里叶变换\n",
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "img = cv2.imread('../name.png', 0)\n",
    "\n",
    "plt.subplot(2, 3, 1)\n",
    "plt.axis('off')\n",
    "plt.title('original')\n",
    "plt.imshow(img, cmap='gray')\n",
    "\n",
    "# 傅里叶变换\n",
    "f_img = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)\n",
    "f_shift = np.fft.fftshift(f_img)\n",
    "\n",
    "result = 20*np.log(cv2.magnitude(f_shift[:, :, 0], f_shift[:, :, 1]))\n",
    "plt.subplot(2, 3, 2)\n",
    "plt.axis('off')\n",
    "plt.title('fft')\n",
    "plt.imshow(result, cmap='gray')\n",
    "\n",
    "# 傅里叶逆变换\n",
    "f_ishift = np.fft.ifftshift(f_shift)\n",
    "img_back = cv2.idft(f_ishift)\n",
    "img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])\n",
    "plt.subplot(2, 3, 3)\n",
    "plt.axis('off')\n",
    "plt.title('ifft')\n",
    "plt.imshow(img_back, cmap='gray')\n",
    "\n",
    "# 高通滤波\n",
    "fshift = np.fft.fftshift(f_img)\n",
    "rows, cols = img.shape\n",
    "crow, ccol = int(rows / 2), int(cols / 2)  # 中心点\n",
    "fshift[crow - 30:crow + 30, ccol - 30:ccol + 30] = 0\n",
    "\n",
    "f_ishift = np.fft.ifftshift(fshift)\n",
    "img_back = cv2.idft(f_ishift)\n",
    "img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])\n",
    "\n",
    "result = 20 * np.log(cv2.magnitude(fshift[:, :, 0], fshift[:, :, 1]))\n",
    "result = (result - np.min(result)) / (np.max(result) - np.min(result)) * 255\n",
    "\n",
    "plt.subplot(2, 3, 4)\n",
    "plt.axis('off')\n",
    "plt.title('original')\n",
    "plt.imshow(img, cmap='gray')\n",
    "\n",
    "plt.subplot(2, 3, 5)\n",
    "plt.axis('off')\n",
    "plt.title('fft')\n",
    "plt.imshow(result, cmap='gray')\n",
    "\n",
    "plt.subplot(2, 3, 6)\n",
    "plt.axis('off')\n",
    "plt.title('ifft')\n",
    "plt.imshow(img_back, cmap='gray')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.7 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "42d820d8758cde2badbeb8f7eaaa44975ccec32144b366942c17254cc50801f8"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
